package com.wolfalpha.lwtool.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;
import org.apache.http.ParseException;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.wolfalpha.lwtool.constant.Application;
import com.wolfalpha.lwtool.constant.Constant;
import com.wolfalpha.lwtool.constant.StringUtils;
import com.wolfalpha.lwtool.db.DBDao;
import com.wolfalpha.lwtool.map.MapsAndLists;
import com.wolfalpha.lwtool.service.BaseService;
import com.wolfalpha.lwtool.service.SaveService;
import com.wolfalpha.lwtool.service.ZQService;
import com.wolfalpha.lwtool.vo.DB;
import com.wolfalpha.lwtool.vo.Job;
import com.wolfalpha.lwtool.vo.JobInfo;

public class BaseServiceImpl implements BaseService {
	@SuppressLint("SimpleDateFormat")
	public static SimpleDateFormat yfr = new SimpleDateFormat("yyyy-MM-dd");
	@SuppressLint("SimpleDateFormat")
	public static SimpleDateFormat yfr1 = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	private List<Integer> js = new ArrayList<Integer>();
	private DBDao dao = null;
	private List<DB> dbs;
	private Context context;
	private ZQService zqSrv;
	private SaveService saveService;
	private boolean inzq = false;
	private boolean lock = false;
	private String time;
	private int frequ = 1;// 频率
	private int count = 0;
	private Timer timerStatic;
	private Thread dyThread;
	protected Timer timerDy;

	public BaseServiceImpl(Context context) {
		this.context = context;
		zqSrv = new ZQServiceImpl();
		saveService = new SaveServiceImpl();
		dao = Application.getDao(context);
		init();
	}

	public String getNowTime() {
		Calendar cal = Calendar.getInstance();
		Date date = cal.getTime();
		return yfr1.format(date);
	}

	/**
	 * 初始化环境变量
	 */
	public void init() {
		lock = false;
		dbs = dao.query();
		js.clear();
		MapsAndLists.getJobs().clear();
		for (DB db : dbs) {
			js.add(db.getId());
		}

		Calendar cal = Calendar.getInstance();
		Date date = cal.getTime();
		// time = "2015-04-08";
		time = yfr.format(date);

		SharedPreferences shp = PreferenceManager
				.getDefaultSharedPreferences(context);
		frequ = shp.getInt("frequency", 0) + 1;
		if (frequ >= 7) {
			frequ = 60;
		}
	}

	/**
	 * 中断线程
	 */
	@Override
	public void stopWork(boolean stop) {
		if (stop) {
			if (timerStatic != null) {
				timerStatic.cancel();
			}
			if (timerDy != null) {
				timerDy.cancel();
			}
			if(dyThread!=null){
				//dyThread.destroy();
				dyThread=null;
			}
			inzq = false;
		}
	}

	/**
	 * 静态抓取 刷新频率
	 */
	@Override
	public void stayZQ() {
		if (inzq)
			return;
		inzq = true;
		sendMsg(Application.N_MAIN, "抓取开始");
		timerStatic = new Timer();
		MyTask mt = new MyTask();
		timerStatic.schedule(mt, 1000, frequ * 60000);// 根据设置
	}

	/**
	 * 动态抓取 点击一次抓取一次
	 */
	@Override
	public void dynamicZQ() {
		if (inzq){
			
			return;
		}
			
		init();
		
		inzq = true;
		new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						
						sendMsg(Application.N_DYNAMIC, "开始抓取");
						
						// 第一步:获取所有&存入本地
						if (!lock){
							System.out.println("mmmmmmmmmmmmmmmmmmmmmm");
							getListOfJobs();
						}
						if (!lock) {
							// 第二步:获取单个&存入远程
							MyTimerTask mt = new MyTimerTask();
							mt.setCount(MapsAndLists.getJobs().size());
							timerDy = new Timer();
							timerDy.schedule(mt, 100, 1000);
						}
						
					} catch (InterruptedException e) {
						e.printStackTrace();
					} catch (ExecutionException e) {
						e.printStackTrace();
					}
					
				}
			}).start();
	}

	/**
	 * 监听刷新
	 */
	public boolean getRefreshJobs() throws InterruptedException,
			ExecutionException {

		System.out.println("Now time:" + getNowTime());

		init();
		count++;
		String str0 = "第" + count + "次刷新|";
		if (js.size() == 0)
			js.add(7278);// 设置默认
		System.out.println("js=" + js);
		System.out.println("MapJobs" + MapsAndLists.getJobs().toString());
		List<Job> jobs;

		if (MapsAndLists.getJobs().size() == 0) {
			jobs = zqSrv.getRefreshJobs(Constant.listUrl,
					Constant.getRefreshMap(js.get(js.size() - 1)));
			System.out.println("refresh1id = " + js.get(js.size() - 1));
		} else {
			int x = MapsAndLists.getJobs()
					.get(MapsAndLists.getJobs().size() - 1).getId();
			jobs = zqSrv.getRefreshJobs(Constant.listUrl,
					Constant.getRefreshMap(x));
			System.out.println("refresh2id = " + x);
		}
		if (jobs == null) {
			sendMsg(Application.N_MAIN, str0 + "没有更新");
			return false;
		}

		for (Job jb : jobs) {
			DB db = new DB();
			db.setId(jb.getId());
			db.setTime(String.valueOf(jb.getPublishDate()));
			db.setTitle(String.valueOf(jb.getJobTitle()));
			db.setMdate(getNowTime());
			if (!String.valueOf(jb.getPublishDate()).equals(time)) {
				String str = str0 + "该记录已经过期[id=" + db.getId() + "]";
				System.out.println(str);
				if (!js.contains(db.getId()))
					dao.addSingleDB(db);
				sendMsg(Application.N_MAIN, str);
				continue;
			} else if (js == null || !js.contains(db.getId())) {
				MapsAndLists.addJob(jb);
				dao.addSingleDB(db);
				System.out.println("Added Success!");
				String str = str0 + "增加并写入本地[id=" + db.getId() + "]";
				System.out.println(str);
				sendMsg(Application.N_MAIN, str);
			} else {
				System.out.println("Already exist!");
				String str = str0 + "该记录已存在本地[id=" + db.getId() + "]";
				System.out.println(str);
				sendMsg(Application.N_MAIN, str);
			}
		}
		if (MapsAndLists.getJobs().size() == 0) {
			System.out.println("无");
			return false;
		}
		return true;

	}

	/**
	 * 正常抓取
	 * 
	 * @throws InterruptedException
	 * @throws ExecutionException
	 */
	public void getListOfJobs() throws InterruptedException, ExecutionException {
		lock = true;
		List<Job> jobs = zqSrv.getJobs(Constant.listUrl, Constant.getHeadMap());
		if (jobs == null) {
			lock = false;
			return;
		}
		sendMsg(Application.N_DYNAMIC, "抓取1次");
		// 收集更多的
		// 循环5次
		for (int i = 0; i < 5; i++) {
			sendMsg(Application.N_DYNAMIC, "抓取" + (i + 2) + "次");
			List<Job> mjbs = zqSrv.getMoreJobs(Constant.listUrl,
					Constant.getMoreMap(jobs.get(jobs.size() - 1).getId()));
			if (mjbs != null) {
				for (Job _jb : mjbs) {
					jobs.add(_jb);
				}
			} else {
				System.out.println("循环" + i + "没有更多");
			}
		}
		for (Job jb : jobs) {
			DB db = new DB();
			db.setId(jb.getId());
			db.setTime(String.valueOf(jb.getPublishDate()));
			db.setTitle(String.valueOf(jb.getJobTitle()));
			db.setMdate(getNowTime());
			if (!String.valueOf(jb.getPublishDate()).equals(time)) {
				String str = "该记录已经过期[id=" + db.getId() + "]";
				sendMsg(Application.N_DYNAMIC, str);
				continue;
			} else if (js == null || !js.contains(db.getId())) {
				MapsAndLists.addJob(jb);
				dao.addSingleDB(db);
				System.out.println("Added Success!");
				String str = "增加并写入本地[id=" + db.getId() + "]";
				sendMsg(Application.N_DYNAMIC, str);
			} else {
				System.out.println("Already exist!");
				String str = "该记录存在本地[id=" + db.getId() + "]";
				sendMsg(Application.N_DYNAMIC, str);
			}
		}
		lock = false;
	}

	/**
	 * 不断抓取
	 * 
	 * @author ttStudio
	 * 
	 */
	public class MyTask extends TimerTask {
		@Override
		public void run() {
			try {
				boolean b = getRefreshJobs();
				if (b) {
					System.out.println("MapJobs2"
							+ MapsAndLists.getJobs().toString());
					MyTimerTask mt = new MyTimerTask();
					mt.setCount(MapsAndLists.getJobs().size());
					if (timerDy == null)
						timerDy = new Timer();
					timerDy.schedule(mt, 100, 200);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 存入数据
	 * 
	 * @author ttStudio
	 * 
	 */
	public class MyTimerTask extends TimerTask {
		int count = 0;
		private int max = MapsAndLists.getJobs().size();

		public void setCount(int c) {
			max = c;
		}

		@Override
		public void run() {
			lock = true;
			try {
				if (count >= max) {
					sendMsg(Application.N_FRONT,
							"FINISH！记录数量：" + String.valueOf(max));
					MapsAndLists.getJobInfos().clear();
					inzq = false;
					this.cancel();
					lock = false;
					return;
				}
				JobInfo info = zqSrv.getInfo(
						Constant.infoUrl,
						Constant.getInfoMap(String.valueOf(MapsAndLists
								.getJobs().get(count).getId())));
				MapsAndLists.addJobInfo(info);
				String str = (String) info.getJobTitle();
				sendMsg(Application.N_FRONT, "开始存入远程一条记录" + count + ":\n["
						+ str + "]");
				publishJob(info);
				sendMsg(Application.N_FRONT, "GET");
				count++;
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			lock = false;
		}
	}

	/**
	 * 发送广播
	 * 
	 * @param Object
	 */
	private void sendMsg(String activity, Object obj) {
		Intent mIntent = new Intent(activity);
		mIntent.putExtra("msg", String.valueOf(obj));
		// 发送广播
		context.sendBroadcast(mIntent);
	}

	/**
	 * 发布
	 * 
	 * @param jinfo
	 */
	public void publishJob(final JobInfo jinfo) {
		try {
			 saveService.publishJob(
			 String.valueOf(jinfo.getJobTitle()),
			 StringUtils.type2Int(String.valueOf(jinfo.getJobType())),
			 String.valueOf(jinfo.getLinkMan()),
			 String.valueOf(jinfo.getTelephone()),
			 StringUtils.region2Int(String.valueOf(jinfo.getWorkAddress())),
			 String.valueOf(jinfo.getWorkAddress()),
			 StringUtils.getSalary(String.valueOf(jinfo.getSalary())),
			 StringUtils.wage2Int(String.valueOf(jinfo.getSalary())),
			 StringUtils.time2Int(String.valueOf(jinfo.getWorkTime())),
			 String.valueOf(jinfo.getWorkDate()), jinfo.getNeedCount(),
			 String.valueOf(jinfo.getJobTitle()),
			 String.valueOf(jinfo.getDetailMsg()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取json数据
	 * 
	 */
	@Override
	public String getJsonById(String id) {
		return zqSrv.postData(Constant.infoUrl, Constant.getInfoMap(id));
	}

}
